import axios from 'axios'
import router from '@/router'
import { ElMessage } from 'element-plus'

// axios默认配置
axios.defaults.timeout = 20000 // 超时时间
// axios.defaults.baseURL = 'localhost'


// 整理数据
axios.defaults.transformRequest = function (data) {
    data = JSON.stringify(data)
    return data
}

// 路由请求拦截
axios.interceptors.request.use(
    config => {
        config.headers['Content-Type'] = 'application/json;charset=UTF-8'
        config.headers['token'] = localStorage.getItem('token');
        return config
    },
    error => {
        return Promise.reject(error.response)
    })

// 路由响应拦截
axios.interceptors.response.use(
    response => {
        // console.log(response);
        if (response.data.success === false) {
            return this.$message.error(response.data.errDesc)
        } else {
            if(response.data.msg=='身份信息过期,请重新登录'){
                localStorage.removeItem('token');
                // this.$message.error(response.data.msg)
                ElMessage.error('身份信息过期,请重新登录')
                //休眠1秒
                setTimeout(() => {
                    router.push('/login')
                }, 1000);
            }
            //如果响应头中包含 currenttime 就返回response
            // console.log(response.headers);
            
            if (response.headers.currenttime) {
                return response
            }
            return response.data
        }
    },
    error => {
        return Promise.reject(error.response) // 返回接口返回的错误信息
    })
export default axios